Learn in 10 minutes

Learn in 10 minutes

10 分钟快速学会 Python

编程语言

Python 是一种高级、解释型的编程语言,以其简洁的语法和强大的功能而闻名。本教程将基于最新的 Python 3.13+ 版本,让你快速学会 Python。

1. 编写你的第一个 Python 程序

我们从一个简单的程序开始,创建一个名为 hello.py 的文件,并输入以下代码:

print("Hello, World!")

保存文件后,在终端或命令行中运行以下命令:

python hello.py

运行后,屏幕将输出:

Hello, World!

这个简单的程序演示了 Python 的基本输出功能。print() 函数用于在控制台显示文本信息。

2. 基本语法

Python 的基本语法非常简单且易于理解。Python 使用缩进来表示代码块,而不是像其他语言使用大括号{}

# 这是一个注释
print("Hello, World!")

Python 的基本语法规则:

  • 缩进:默认使用 4 个空格表示一个代码块的层级。例如,函数或循环内的代码必须缩进。
  • 注释:单行注释以 # 开头,多行注释使用三引号 """'''
  • 语句:通常每行一条语句,无需以分号 ; 结尾。
  • 代码块:由缩进定义,例如 iffor 或函数体。

以下是一个包含多行注释的示例:

"""
这是一个多行注释,
可以跨越多行。
"""

缩进是 Python 语法的重要特征,用于定义代码块的层次结构:

if True:
    print("这行代码被缩进了")
    print("这行也是")
print("这行没有缩进")

3. 变量与数据类型

在 Python 中,变量是用来存储数据的容器。Python 是动态类型语言,这意味着您不需要预先声明变量的类型。

变量的基本命名规则

  • 变量名只能包含字母、数字和下划线
  • 变量名不能以数字开头
  • 变量名区分大小写
  • 不能使用 Python 的关键字作为变量名

变量的类型由赋值的内容决定。Python 主要的基本数据类型如下

  • 整数 (int):如 42-10,无大小限制。
  • 浮点数 (float):如 3.142.5e3(科学计数法)。
  • 字符串 (str):如 "hello"'world',使用单引号或双引号。
  • 布尔值 (bool)TrueFalse
  • 空值 (None):用 None 表示空或无值。

Python 支持类型提示(Type Hints)以提高代码可读性,但这些提示仅用于静态检查和 IDE 的类型提示,不影响运行时的行为:

name: str = "Alice"
age: int = 25

3.1 数值类型(Number)

Python 支持三种数值类型:整数 (int)、浮点数 (float) 和复数 (complex)。

# 整数
age = 25
population = 1000000

# 浮点数
temperature = 36.5
pi = 3.14159

# 复数
complex_num = 3 + 4j

3.2 字符串 (String)

字符串是字符的序列,用单引号或双引号括起来。

single_quote = '单引号字符串'
double_quote = "双引号字符串"
multiline = """这是一个
多行字符串"""

字符串支持多种操作:

text = "Python编程"
print(len(text))        # 字符串长度
print(text.upper())     # 转换为大写
print(text.lower())     # 转换为小写
print(text[0])          # 访问第一个字符
print(text[2:6])        # 字符串切片

3.3 布尔类型 (Boolean)

布尔类型只有两个值:TrueFalse

is_active = True
is_complete = False

# 布尔运算
result1 = True and False  # False
result2 = True or False   # True
result3 = not True        # False

3.4 空值类型 (None)

None 表示空值或无值的状态。

value = None

if value is None:
    print("值为空")

4. 数据结构

Python 提供了多种内置数据结构,用于存储和操作数据。以下是常用的数据结构及其用法。

4.1 列表 (List)

列表是一个有序且可变的集合。你可以添加、删除或修改列表中的元素。列表使用方括号 [] 定义。

numbers = [1, 2, 3, 4, 5]
numbers.append(6)      # 添加元素
numbers.insert(0, 0)   # 在指定位置插入
numbers.remove(3)      # 删除指定值
numbers[0] = 10        # 修改元素
print(numbers)         # [10, 2, 4, 5, 6]

列表切片(Slice)操作,用于访问子列表:

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])    # 输出: [20, 30, 40]
print(numbers[:3])     # 输出: [10, 20, 30]
print(numbers[-2:])    # 输出: [40, 50]

列表推导式(List Comprehension):

squares = [x**2 for x in range(5)]
print(squares)         # [0, 1, 4, 9, 16]

even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)    # [0, 4, 16, 36, 64]

4.2 元组 (Tuple)

元组是一个有序但不可变的集合。一旦创建,你就不能修改元组中的元素。元组使用圆括号 () 定义。由于其不可变性,元组通常比列表更快,并且可以用作字典的键。

point = (10, 20)
x, y = point  # 解包
print(x, y)   # 输出: 10 20

单个元素的元组需要逗号:

single_tuple = (42,)

4.3 字典 (Dict)

字典是无序(在 Python 3.7+ 版本中是有序的)的键值对 (key-value pair) 集合。每个键都是唯一的,并与一个值相关联。字典使用花括号 {} 定义。

student = {
    "name": "张三",
    "age": 20,
    "major": "计算机科学"
}

# 访问和修改字典
print(student["name"])
student["age"] = 21
student["gpa"] = 3.8

# 安全访问
print(student.get("phone", "未提供"))

# 遍历字典
for key, value in student.items():
    print(f"{key}: {value}")

字典推导式:

# 创建平方字典
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 条件字典推导
even_squares_dict = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares_dict)  # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

4.4 集合 (Set)

集合是一个无序且不包含重复元素的集合。使用大括号 {}set() 定义

# 创建集合
fruits = {"苹果", "香蕉", "橙子"}
numbers = set([1, 2, 3, 3, 4, 4, 5])  # 自动去重
print(numbers)  # {1, 2, 3, 4, 5}

# 集合操作
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

print(set1 | set2)  # 并集: {1, 2, 3, 4, 5, 6}
print(set1 & set2)  # 交集: {3, 4}
print(set1 - set2)  # 差集: {1, 2}
print(set1 ^ set2)  # 对称差集: {1, 2, 5, 6}

5. 运算和操作符

Python 提供了丰富的运算符来执行各种计算和比较操作。包括算术、比较、逻辑、位运算符和身份操作符。

  • 算术运算符+, -, *, /, //(整除),%(取模),**(幂)。
  • 比较运算符==, !=, >, <, >=, <=
  • 逻辑运算符and, or, not
  • 成员运算符in, not in
  • 身份操作符: is, is not

5.1 算术运算符

在 Python 中,算术运算符用于执行数学运算。并且优先级遵循数学规则(例如,** 优先级高于 + 和 -)。如果需要改变优先级,可以使用括号 ()。

a, b = 10, 3

print(f"加法: {a + b}")      # 13
print(f"减法: {a - b}")      # 7
print(f"乘法: {a * b}")      # 30
print(f"除法: {a / b}")      # 3.333...
print(f"整除: {a // b}")     # 3
print(f"取模: {a % b}")      # 1
print(f"幂运算: {a ** b}")   # 1000

5.2 比较运算符

在 Python 中,比较运算符用于比较两个值,返回布尔值(True 或 False)。

x, y = 5, 10

print(f"等于: {x == y}")     # False
print(f"不等于: {x != y}")   # True
print(f"大于: {x > y}")      # False
print(f"小于: {x < y}")      # True
print(f"大于等于: {x >= y}") # False
print(f"小于等于: {x <= y}") # True

5.3 逻辑运算符

在 Python 中,逻辑运算符用于组合或操作布尔值(True 或 False),通常用于条件判断。

a, b = True, False

print(f"与运算: {a and b}")  # False
print(f"或运算: {a or b}")   # True
print(f"非运算: {not a}")    # False

5.4 身份运算符(Identity Operator)

在 Python 中,is 是一个身份操作符(Identity Operator),用于比较两个对象的身份,即判断两个对象是否是同一个对象(引用相同的内存地址)。它并不比较对象的值是否相等,而是检查它们的内存地址是否一致。

  • is 操作符会检查两个对象的 id() 是否相同。id() 是 Python 中用于获取对象内存地址的内置函数。
  • 它与值比较操作符 == 不同,== 比较的是对象的内容是否相等,而 is 比较的是对象的身份。
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(f"list1 is list2: {list1 is list2}")    # False
print(f"list1 is list3: {list1 is list3}")    # True
print(f"list1 == list2: {list1 == list2}")    # True

5.5 成员运算符

在 Python 中,成员运算符用于测试一个值是否是某个序列(如列表、元组、字符串、集合等)的成员。它们返回布尔值(True 或 False)。

fruits = ["苹果", "香蕉", "橙子"]

print(f"'苹果' in fruits: {'苹果' in fruits}")        # True
print(f"'葡萄' not in fruits: {'葡萄' not in fruits}")  # True

6. 控制流

Python 提供了多种控制流语句,用于控制程序的执行顺序。

6.1 if 条件语句

if 语句用于条件判断。它会评估一个表达式,如果表达式为 True,则执行其下的代码块。你还可以使用 elifelse 来处理更复杂的条件。

age = 20
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teen")
else:
    print("Child")

6.2 for 循环语句

for 循环用于遍历一个可迭代对象(如列表、元组、字符串或范围)。

# 遍历列表
fruits = ["苹果", "香蕉", "樱桃"]
for fruit in fruits:
    print(fruit)

# 使用 range() 函数进行循环
for i in range(5):
    print(i)  # 输出: 0, 1, 2, 3, 4

6.3 while 循环语句

while 循环会在其条件保持为 True 的情况下,持续执行一个代码块。

count = 0
while count < 5:
    print(count)
    count += 1
  • break 和 continuebreak 退出循环,continue 跳过当前迭代。
for i in range(10):
    if i == 5:
        break
    if i % 2 == 0:
        continue
    print(i)  # 输出: 1, 3

6.4 match 语句

从 Python 3.10 开始引入的 match 语句提供了强大的结构化模式匹配功能,可以看作是更高级的 if/elif/else 链。

http_status = 200

match http_status:
    case 200 | 201:
        print("成功")
    case 404:
        print("未找到")
    case 500:
        print("服务器错误")
    case _:  # _ 是一个通配符,匹配任何其他情况
        print("未知状态")

7. 输入与输出

7.1 基本输入输出

Python 中使用 input() 函数获取用户输入,使用 print() 函数输出信息。

# 获取用户输入
name = input("请输入您的姓名: ")
age = int(input("请输入您的年龄: "))

# 输出信息
print("欢迎", name)
print("您今年", age, "岁")

7.2. 格式化输出(f-string)

f-string (格式化字符串字面值) 是 Python 3.6+ 引入的一种非常方便和强大的字符串格式化方法。你可以在字符串前面加上一个 f 或 F,然后用花括号 {} 直接嵌入变量或表达式。

user = "Alice"
items = 3
total_cost = 45.5

# 使用 f-string 创建格式化的消息
message = f"用户 {user} 购买了 {items} 件商品,总价为 ${total_cost:.2f}。"

print(message)
# 表达式也可以直接放入 f-string
print(f"2 + 3 的结果是 {2 + 3}")

f-string 中的表达式和函数调用

width = 10
height = 5

# 在 f-string 中使用表达式
area = f"矩形面积: {width * height}"
print(area)

# 调用函数
text = "python"
formatted = f"大写: {text.upper()}, 长度: {len(text)}"
print(formatted)

f-string 支持格式化选项:

pi = 3.14159265359
large_number = 1234567

# 数字格式化
print(f"Pi (2位小数): {pi:.2f}")
print(f"Pi (4位小数): {pi:.4f}")
print(f"大数字 (千分位): {large_number:,}")
print(f"百分比: {0.85:.1%}")

# 字符串对齐
name = "Python"
print(f"左对齐: '{name:<10}'")
print(f"右对齐: '{name:>10}'")
print(f"居中: '{name:^10}'")

f-string 日期和时间格式化

from datetime import datetime

now = datetime.now()
print(f"当前时间: {now}")
print(f"格式化时间: {now:%Y-%m-%d %H:%M:%S}")
print(f"只显示日期: {now:%Y年%m月%d日}")

9. 函数

Python 中函数是可重用的代码块,用于执行特定任务。函数使用 def 关键字定义,支持默认参数、可变参数和关键字参数。

基本函数定义(Function definition)

def greet(name):
    """问候函数"""
    return f"你好, {name}!"

# 调用函数
message = greet("张三")
print(message)

关键字参数(Keyword Arguments)

关键字参数(keyword arguments)是指在调用函数时,使用 参数名=值 的形式传递参数。

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Alice"))          # 输出: Hello, Alice!
print(greet("Bob", "Hi"))     # 输出: Hi, Bob!

可变参数(Variable parameters)

可变参数(variable arguments)是指函数可以接受任意数量的参数。可变参数分为两种主要类型:位置可变参数和关键字可变参数

# 位置可变参数(*args)
def sum_numbers(*args):
    return sum(args)

print(sum_numbers(1, 2, 3, 4))  # 输出: 10

# 关键字可变参数(**kwargs)
def print_kwargs(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_kwargs(name="Alice", age=25, city="Beijing")

函数注解(Function Annotations)

Python 中函数注解是为函数、参数和返回值添加描述的一种特性,通常用于提高代码可读性、文档化。

def calculate_area(length: float, width: float) -> float:
    """计算矩形面积"""
    return length * width

def process_user(name: str, age: int, active: bool = True) -> dict:
    """处理用户信息"""
    return {
        "name": name,
        "age": age,
        "active": active
    }

10. Lambda 表达式

Lambda 表达式用于创建匿名函数,是创建小型匿名函数的简洁方式。

square = lambda x: x ** 2
print(square(5))  # 输出: 25

常用于高阶函数如 mapfilter

numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # 输出: [1, 4, 9, 16]

11. 类和对象

Python 支持面向对象编程,使用 class 关键字定义类:

class Person:
    """人员类"""
    
    def __init__(self, name, age):
        """构造函数"""
        self.name = name
        self.age = age
    
    def introduce(self):
        """自我介绍方法"""
        return f"我是{self.name}, 今年{self.age}岁"
    
    def have_birthday(self):
        """过生日方法"""
        self.age += 1
        return f"{self.name}过生日了, 现在{self.age}岁"

# 创建对象
person1 = Person("张三", 25)
person2 = Person("李四", 30)

print(person1.introduce())
print(person2.have_birthday())

11.1 类属性和实例属性

在 Python 中,类属性和实例属性是类和对象中用于存储数据的两种不同类型的属性

  • 类属性 (Class Attribute)

类属性是定义在类中、但在任何方法之外的属性,属于类本身,而不是类的某个实例。类属性在类的所有实例之间是共享的。

  • 实例属性 (Instance Attribute)

实例属性是定义在类的方法中(通常是 init 方法中),通过 self 绑定的属性,属于类的具体实例。

class Student:
    # 类属性
    school = "Stanford University"
    student_count = 0
    
    def __init__(self, name, major):
        # 实例属性
        self.name = name
        self.major = major
        Student.student_count += 1
    
    @classmethod
    def get_student_count(cls):
        """类方法"""
        return cls.student_count
    
    @staticmethod
    def is_valid_age(age):
        """静态方法"""
        return 0 < age < 150

# 使用示例
student1 = Student("张三", "计算机科学")
student2 = Student("李四", "数学")

print(f"学校: {Student.school}")
print(f"学生总数: {Student.get_student_count()}")
print(f"年龄是否有效: {Student.is_valid_age(20)}")

11.2 类的继承

在 Python 中,类的继承是一种面向对象编程(OOP)的机制,允许一个类(称为子类或派生类)从另一个类(称为父类或基类)继承属性和方法。通过继承,子类可以重用父类的代码,同时也可以扩展或修改父类的功能。

class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species
    
    def make_sound(self):
        return f"{self.name} 发出了声音"
    
    def info(self):
        return f"{self.name} 是一只 {self.species}"

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name, "犬类")
        self.breed = breed
    
    def make_sound(self):
        return f"{self.name} 汪汪叫"
    
    def fetch(self):
        return f"{self.name} 去捡球了"

class Cat(Animal):
    def __init__(self, name, color):
        super().__init__(name, "猫科")
        self.color = color
    
    def make_sound(self):
        return f"{self.name} 喵喵叫"
    
    def climb(self):
        return f"{self.name} 爬上了树"

# 使用继承
dog = Dog("旺财", "金毛")
cat = Cat("咪咪", "橙色")

print(dog.info())
print(dog.make_sound())
print(dog.fetch())

print(cat.info())
print(cat.make_sound())
print(cat.climb())

11.3 特殊方法(魔术方法)

在 Python 中,魔术方法(Magic Methods)或称为特殊方法(Special Methods),是一类以双下划线开头和结尾的内置方法,用于定义类的特殊行为或实现特定的功能。它们通常由 Python 解释器在特定场景下自动调用,而不是由开发者显式调用,因此被称为“魔术方法”。

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def __str__(self):
        """字符串表示"""
        return f"Rectangle({self.width}x{self.height})"
    
    def __repr__(self):
        """官方字符串表示"""
        return f"Rectangle(width={self.width}, height={self.height})"
    
    def __eq__(self, other):
        """相等比较"""
        if isinstance(other, Rectangle):
            return self.width == other.width and self.height == other.height
        return False
    
    def __lt__(self, other):
        """小于比较(按面积)"""
        if isinstance(other, Rectangle):
            return self.area() < other.area()
        return NotImplemented
    
    def __add__(self, other):
        """加法运算"""
        if isinstance(other, Rectangle):
            return Rectangle(self.width + other.width, self.height + other.height)
        return NotImplemented
    
    def area(self):
        """计算面积"""
        return self.width * self.height

# 使用特殊方法
rect1 = Rectangle(3, 4)
rect2 = Rectangle(5, 6)
rect3 = Rectangle(3, 4)

print(rect1)           # Rectangle(3x4)
print(repr(rect1))     # Rectangle(width=3, height=4)
print(rect1 == rect3)  # True
print(rect1 < rect2)   # True
print(rect1 + rect2)   # Rectangle(8x10)

12. 上下文管理器

上下文管理器是一种确保资源正确获取和释放的机制,主要用于资源管理。例如文件、数据库连接的生命周期,通常与 with 语句配合使用。

12.1 使用上下文管理器

文件操作是一个常见的上下文管理器用例:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

with 语句确保文件在操作完成后自动关闭。

12.2 自定义上下文管理器

通过定义 __enter____exit__ 方法创建自定义上下文管理器:

class DatabaseConnection:
    def __init__(self, database_name):
        self.database_name = database_name
        self.connection = None
    
    def __enter__(self):
        """进入上下文时调用"""
        print(f"连接到数据库: {self.database_name}")
        self.connection = f"连接到{self.database_name}"
        return self.connection
    
    def __exit__(self, exc_type, exc_value, traceback):
        """退出上下文时调用"""
        print(f"关闭数据库连接: {self.database_name}")
        if exc_type:
            print(f"发生异常: {exc_type.__name__}: {exc_value}")
        self.connection = None
        return False  # 不抑制异常

# 使用自定义上下文管理器
with DatabaseConnection("用户数据库") as conn:
    print(f"使用连接: {conn}")
    print("执行数据库操作...")

使用 contextlib 模块实现上下文管理器

from contextlib import contextmanager
import time

@contextmanager
def timer(operation_name):
    """计时上下文管理器"""
    print(f"开始 {operation_name}")
    start_time = time.time()
    try:
        yield
    finally:
        end_time = time.time()
        print(f"{operation_name} 完成,用时: {end_time - start_time:.2f}秒")

# 使用装饰器创建的上下文管理器
with timer("数据处理"):
    # 模拟耗时操作
    time.sleep(1)
    print("处理数据中...")

13. 异常处理

异常处理是程序健壮性的重要保证,Python 提供了完善的异常处理机制, 使用 tryexceptelsefinally 处理异常:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print("Division successful")
finally:
    print("This always runs")

输出:

Cannot divide by zero!
This always runs

14. 文件操作

Python 提供了简单的方法来读写文件,通常结合上下文管理器使用。

14.1 读取文件

读取文本文件内容:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

逐行读取:

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())

14.2 写入文件

写入文本文件:

with open("output.txt", "w") as file:
    file.write("Hello, Python!\n")

追加内容:

with open("output.txt", "a") as file:
    file.write("Appending new content.\n")

15. 模块和包

模块是包含 Python 代码的文件,包是包含多个模块的目录。导入模块使用 import

import math
print(math.sqrt(16))  # 输出: 4.0

自定义模块示例(假设文件名为 mymodule.py):

# mymodule.py
def say_hello():
    return "Hello from module!"

导入并使用:

import mymodule
print(mymodule.say_hello())  # 输出: Hello from module!

16. 作用域和命名空间

16.1 作用域(Scope)

作用域 (Scope) 指的是一个变量可以被访问的区域。Python 遵循 LEGB 规则来查找一个变量:

  • L (Local): 局部作用域,指函数或类方法内部。
  • E (Enclosing): 闭包函数的作用域(即嵌套函数的外层函数)。
  • G (Global): 全局作用域,指模块级别的顶层。
  • B (Built-in): 内置作用域,包含了 print(), len() 等 Python 内置的函数和异常。
x = "global x"

def outer_func():
    x = "enclosing x"
    def inner_func():
        x = "local x"
        print(x) # 访问的是 Local 作用域的 x
    inner_func()
    print(x) # 访问的是 Enclosing 作用域的 x

outer_func()
print(x) # 访问的是 Global 作用域的 x

使用 globalnonlocal 修改作用域变量:

x = "global"
def modify_global():
    global x
    x = "modified"
modify_global()
print(x)  # 输出: modified

16.2 命名空间(Namespace)

命名空间 (Namespace) 是一个从名称到对象的映射。可以把它想象成一个字典,键是变量名,值是变量对应的对象。

Python 中的每个模块、函数、类都有自己的命名空间。这有助于避免命名冲突。你可以使用 globals() 和 locals() 函数来查看当前作用域的命名空间。

a_variable = 10

def some_function():
    b_variable = 20
    # locals() 返回当前局部命名空间的字典
    print(f"Locals: {locals()}")

print(f"Globals: {globals().keys()}") # 打印部分全局命名空间的键
some_function()

17. 生成器

生成器 (Generator) 是一种特殊的迭代器,它允许你按需生成值,而不是一次性创建所有值并存储在内存中。这对于处理大数据集非常高效。

生成器用于惰性计算,通过 yield 关键字返回值:

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(5):
    print(num)  # 输出: 0, 1, 1, 2, 3

18. 多线程

多线程 (Multithreading) 允许你的程序同时执行多个操作。这对于执行 I/O 密集型任务(如网络请求、文件读写)非常有用,因为线程可以在等待 I/O 操作完成时切换到其他任务。

Python 的 threading 模块提供了创建和管理线程的工具。

需要注意的是,由于全局解释器锁 (GIL),Python 的多线程在单个进程中并不能实现真正的 CPU 并行计算,但对于 I/O 密集型任务,性能提升依然显著。

import threading
import time

def worker(thread_name):
    print(f"线程 {thread_name} 开始执行...")
    time.sleep(2) # 模拟耗时操作
    print(f"线程 {thread_name} 执行结束。")

# 创建线程
thread1 = threading.Thread(target=worker, args=("A",))
thread2 = threading.Thread(target=worker, args=("B",))

# 启动线程
thread1.start()
thread2.start()

# 等待所有线程完成
thread1.join()
thread2.join()

print("所有线程已完成。")

19. 异步编程

异步编程 (Asynchronous Programming) 是另一种处理并发任务的方式,特别适合于高 I/O、高并发的场景。它使用事件循环来管理任务,而不是依赖多线程。

Python 通过 asyncio 库和 async/await 语法来支持异步编程。

  • async def: 用于定义一个协程 (coroutine)。
  • await: 用于暂停协程的执行,等待一个可等待对象 (awaitable) 完成。
import asyncio

async def say_hello():
    print("Hello")
    await asyncio.sleep(1) # 非阻塞的休眠,模拟 I/O 操作
    print("World")

async def main():
    # 创建一个任务并等待任务完成
    await asyncio.create_task(say_hello())

# 运行主协程
asyncio.run(main())

输出:

Hello
World